package com.szw.dlyk.config.handler;


import cn.hutool.core.util.BooleanUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.szw.dlyk.constant.Constant;
import com.szw.dlyk.domain.User;
import com.szw.dlyk.dto.UserDtoLogin;
import com.szw.dlyk.result.Result;
import com.szw.dlyk.service.RedisService;
import com.szw.dlyk.util.JwtUtil;
import com.szw.dlyk.util.ResponseUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private RedisService redisService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //登录成功，执行该方法，在该方法中返回json给前端，就行了
        UserDtoLogin user = (UserDtoLogin) authentication.getPrincipal();

        String s = JSONUtil.toJsonStr(user);

        String jwt = JwtUtil.createJWT(s);

        redisService.setValue(Constant.REDIS_JWT_KEY + user.getId(), jwt);

        String rememberMe = request.getHeader("rememberMe");
        if (Boolean.parseBoolean(rememberMe)) {
            redisService.expire(Constant.REDIS_JWT_KEY + user.getId(),Constant.EXPIRE_TIME,TimeUnit.SECONDS);
        }else {
            redisService.expire(Constant.REDIS_JWT_KEY + user.getId(),Constant.DEFAULT_EXPIRE_TIME,TimeUnit.SECONDS);
        }

        //登录成功的统一结果
        Result result = Result.ok(jwt);

        //把Result对象转成json
        String resultJSON = JSONUtil.toJsonStr(result);

        //把Result以json返回给前端
        ResponseUtils.write(response, resultJSON);
    }
}
